package product

import (
	"context"
	"errors"
	"github.com/cloudwego/hertz/pkg/common/hlog"
	"gorm.io/gen"
	"mall_admin_api/biz/config"
	"mall_admin_api/biz/dal"
	"mall_admin_api/biz/factory"
	"mall_admin_api/biz/handler/common"
	"mall_admin_api/biz/model"
	"mall_admin_api/biz/model/admin_product_material"
	"mall_admin_api/biz/pack"
)

type Material struct {
	commonInfo *common.Response
	dao        *dal.InitDAO
}

func NewMaterial(response *common.Response) *Material {
	return &Material{
		commonInfo: response,
		dao:        dal.NewInitDAO(response.GetBizInfo().ID),
	}
}

func (c *Material) logAddMethod(ctx context.Context) context.Context {
	return ctx
}

func (c *Material) GetList(ctx context.Context, req *admin_product_material.GetMaterialListRequest, page, size int) ([]*admin_product_material.Material, int64, error) {
	ctx = c.logAddMethod(ctx)
	var conditions []gen.Condition
	conditions = append(conditions, dal.ProductMaterial.BizID.Eq(c.commonInfo.GetBizInfo().ID))
	if req.GroupID != nil {
		conditions = append(conditions, dal.ProductMaterial.GroupID.Eq(req.GetGroupID()))
	}
	list, total, err := c.dao.ProductMaterialDAO.GetListWithTotal(ctx, &dal.ProductMaterialListParams{
		Condition: conditions,
		Page:      page,
		Size:      size,
	})
	if err != nil {
		hlog.CtxErrorf(ctx, "GetList err: %v", err)
		return nil, 0, err
	}

	var imageList []string
	for _, material := range list {
		imageList = append(imageList, material.URL)
	}

	return pack.GetProductMaterialList(list), total, nil
}

func (c *Material) Delete(ctx context.Context, req *admin_product_material.DeleteMaterialRequest) error {
	ctx = c.logAddMethod(ctx)
	if err := c.dao.ProductMaterialDAO.DeleteProductMaterial(ctx, []gen.Condition{dal.ProductMaterial.ID.In(req.GetIDs()...)}); err != nil {
		hlog.CtxErrorf(ctx, "Delete err: %v", err)
		return err
	}
	return nil
}

func (c *Material) Create(ctx context.Context, req *admin_product_material.CreateMaterialRequest) error {
	ctx = c.logAddMethod(ctx)
	var data = &model.ProductMaterial{
		Name:      req.GetName(),
		BizID:     c.commonInfo.GetBizInfo().ID,
		URL:       req.URL,
		GroupID:   req.GroupID,
		Type:      req.Type,
		CreatedBy: c.commonInfo.GetAdministratorInfo().Nickname,
	}
	if _, err := c.dao.ProductMaterialDAO.CreateProductMaterial(ctx, data); err != nil {
		hlog.CtxErrorf(ctx, "Create err: %v", err)
		return err
	}
	return nil
}

func (c *Material) Upload(ctx context.Context) (*admin_product_material.UploadMaterial, error) {
	ins, ok := factory.GetUploadFactory(c.commonInfo)[config.Values.Upload.Source]
	if !ok {
		hlog.CtxErrorf(ctx, "Upload err: source not exist %s", config.Values.Upload.Source)
		return nil, errors.New("错误的上传工厂类型")
	}
	fileName, err := ins.Upload(ctx)
	if err != nil {
		hlog.CtxErrorf(ctx, "Upload err: %v", err)
		return nil, err
	}
	return &admin_product_material.UploadMaterial{ImagePath: fileName}, nil
}
